<template>
    <li>
        <label>
            <input type="checkbox" :checked="todo.done" @click="handleCheck(todo.id)"/>
            <span v-show="!todo.isEdit">{{ todo.title }}</span>
            <input v-show="todo.isEdit"
                   type="text"
                   :value="todo.title"
                   @blur="handleBlur(todo,$event)"
                   ref="inputTitle"/>
        </label>
        <button class="btn btn-danger" @click="handleDel(todo.id)">删除</button>
        <button v-show="!todo.isEdit" class="btn btn-edit" @click="handleUpdate(todo)">修改</button>
    </li>
</template>

<script>
export default {
    name: "MyItem",
    // props声明接收父组件传过来的todo对象
    props: ['todo'],
    methods: {
        handleCheck(id) {
            this.$bus.$emit('checkTodo', id);
        },
        handleDel(id) {
            if (confirm('确定要删除吗？')) {
                this.$bus.$emit('delTodo', id)
            }
        },
        handleUpdate(todo) {
            // eslint-disable-next-line no-prototype-builtins
            if (todo.hasOwnProperty('isEdit')) {
                todo.isEdit = true;
            } else {
                console.log('已经存在isEdit属性')
                this.$set(todo, 'isEdit', true);
            }
            // 直接获取焦点是不行的，因为此时的input是处于隐藏状态，通过isEdit属性控制，vue先执行完方法，在重新解析模板
            // this.$refs.inputTitle.focus()

            // nextTick指定的回调函数会在dom节点更新完毕后执行
            this.$nextTick(function () {
                this.$refs.inputTitle.focus() // 必须等vue重新解析模板后再获取焦点
            })
        },
        handleBlur(todo, event) {
            todo.isEdit = false;
            if (!event.target.value.trim()) return alert('输入不能为空')
            this.$bus.$emit('updateTodo', todo.id, event.target.value)
        }
    }
}
</script>

<style scoped>
/*item*/
li {
    list-style: none;
    height: 36px;
    line-height: 36px;
    padding: 0 5px;
    border-bottom: 1px solid #ddd;
}

li label {
    float: left;
    cursor: pointer;
}

li label li input {
    vertical-align: middle;
    margin-right: 6px;
    position: relative;
    top: -1px;
}

li button {
    float: right;
    display: none;
    margin-top: 3px;
}

li:before {
    content: initial;
}

li:last-child {
    border-bottom: none;
}

li:hover {
    background-color: #ddd;
}

li:hover button {
    display: block;
}
</style>